<!--转换不到账单记录表-->
<script setup lang="ts">
    import {AxiosPromise} from "axios";

    defineOptions({
        name: "NoMatchRecord",
        inheritAttrs: false,
    });

    import {ElLoading, UploadFile} from "element-plus";
    import {
        getNoMatchRecordPage,
        getNoMatchRecordForm,
        saveNoMatchRecord,
        deleteNoMatchRecord,
        importNoMatchRecord,
        exportNoMatchRecord,
				reBill,
				ignoreBill,
				reBillAll,
				fallback,
				getDataInfo
    } from "@/api/noMatchRecord";
		import { listAll } from "@/api/store";
		import lodash from "lodash-es";

    const queryFormRef = ref(ElForm);
    const dataFormRef = ref(ElForm);

    const loading = ref(false);
    const tmLoading = ref(false);
    const ids = ref<number[]>([]);
    const total = ref(0);
    const tmTotal = ref(0);
		const storeList = ref<[]>([]);
		const filterStoreList = ref<[]>([]);
		const dateList = ref<[]>([]);
		const dataText = ref<any>('');
		const dataJson = ref<any>({});
		const activeTab = ref<any>('one');

    const queryParams = reactive<any>({
        pageNum: 1,
        pageSize: 20,
    });

    const noMatchRecordList = ref<[]>([]);

    const dialog = reactive<DialogOption>({
        visible: false,
    });
    const importDialog = reactive<DialogOption>({
        title: "转换不到账单记录表数据导入",
        visible: false,
    });
		const repairDialog = reactive<DialogOption>({
			title: '原始数据',
			visible: false,
		});

    const excelFile = ref<File>();
    const excelFilelist = ref<File[]>([]);
    const formData = reactive<any>({});

    const rules = reactive({
        storeId: [{ required: true, message: "请输入店铺ID", trigger: "blur" }],
        dataId: [{ required: true, message: "请输入原始单据id", trigger: "blur" }],
        tableNamePreFix: [{ required: true, message: "请输入表名前缀", trigger: "blur" }],
        dictCode: [{ required: true, message: "请输入字典类型CODE", trigger: "blur" }],
        billMonth: [{ required: true, message: "请输入账单月份", trigger: "blur" }],
        dataMap: [{ required: true, message: "请输入原始数据", trigger: "blur" }],
        deleted: [{ required: true, message: "请输入0 未删除 1 已删除", trigger: "blur" }],
    });


		function getAllStore() {
			listAll().then((response) => {
				storeList.value = []
				const group_store = lodash.groupBy(response.data, 'storeKeyName');
				for (let key in group_store) {
					storeList.value.push({'label': key, 'options': group_store[key]})
					filterStoreList.value = storeList.value
				}
			})
		}

    /**
     * 查询
     */
    function handleQuery() {
			if (activeTab.value === 'one') {
				loading.value = true;
				if (lodash.size(dateList.value) > 0){
					lodash.set(queryParams, 'startDate', dateList.value[0])
					lodash.set(queryParams, 'endDate', dateList.value[1])
				}else{
					queryParams.startDate = ''
					queryParams.endDate = ''
				}
				getNoMatchRecordPage(queryParams)
					.then(({ data }) => {
						noMatchRecordList.value = data.list;
						for (let item of noMatchRecordList.value) {
							if (item.dataMap !== '' && item.dataMap !== null && item.dataMap !== undefined) {
								lodash.set(item, 'dataJson', JSON.parse(item.dataMap))
							}
						}
						total.value = data.total;
					})
					.finally(() => {
						loading.value = false;
					});
			}else if (activeTab.value === 'two') {
				tmLoading.value = true;
				if (lodash.size(dateList.value) > 0){
					lodash.set(queryParams, 'startDate', dateList.value[0])
					lodash.set(queryParams, 'endDate', dateList.value[1])
				}else{
					queryParams.startDate = ''
					queryParams.endDate = ''
				}
				getNoMatchRecordPage(queryParams)
					.then(({ data }) => {
						noMatchRecordList.value = data.list;
						for (let item of noMatchRecordList.value) {
							if (item.dataMap !== '' && item.dataMap !== null && item.dataMap !== undefined) {
								lodash.set(item, 'dataJson', JSON.parse(item.dataMap))
							}
						}
						tmTotal.value = data.total;
					})
					.finally(() => {
						tmLoading.value = false;
					});
			}
    }

		function tabChange() {
			if (activeTab.value === 'one') {
				queryParams.storeId = ''
				queryParams.billType = ''
				filterStoreList.value = storeList.value
				queryParams.pageNum = 1
			}else if (activeTab.value === 'two') {
				filterStoreList.value = lodash.filter(storeList.value, (item: any) => item.label === '天猫')
				queryParams.storeId = ''
				queryParams.pageNum = 1
				queryParams.billType = '天猫资金流水'
			}
			handleQuery()
		}

    /**
     * 重置查询
     */
    function resetQuery() {
        queryFormRef.value.resetFields();
        queryParams.pageNum = 1;
        handleQuery();
    }

    /**
     * 行checkbox change事件
     */
    function handleSelectionChange(selection: any) {
        ids.value = selection.map((item: any) => item.id);
    }

    /**
     * 打开字典类型表单弹窗
     *
     * @param dicTypeId 字典类型ID
     */
    function openDialog(id?: number) {
        dialog.visible = true;
        if (id) {
            dialog.title = "修改转换不到账单记录表";
            getNoMatchRecordForm(id).then(({ data }) => {
                Object.assign(formData, data);
            });
        } else {
            dialog.title = "新增转换不到账单记录表";
        }
    }

    /**
     * 字典类型表单提交
     */
    function handleSubmit() {
        dataFormRef.value.validate((isValid: boolean) => {
            if (isValid) {
                loading.value = false;
                saveNoMatchRecord(formData)
                    .then(() => {
                        ElMessage.success("保存成功");
                        closeDialog();
                        handleQuery();
                    })
                    .finally(() => (loading.value = false));
            }
        });
    }

    /**
     * 关闭弹窗
     */
    function closeDialog() {
        dialog.visible = false;
        resetForm();
    }

    /**
     * 重置表单
     */
    function resetForm() {
        dataFormRef.value.resetFields();
        dataFormRef.value.clearValidate();

        formData.id = undefined;
    }

    /**
     * 删除转换不到账单记录表
     */
    function handleDelete(id?: number) {
        const dictTypeIds = [id || ids.value].join(",");
        if (!dictTypeIds) {
            ElMessage.warning("请勾选删除项");
            return;
        }

        ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            deleteNoMatchRecord(dictTypeIds).then(() => {
                ElMessage.success("删除成功");
                resetQuery();
            });
        });
    }

    /** 打开导入弹窗 */
    async function openImportDialog() {
        importDialog.visible = true;
    }

    /**
     * Excel文件change事件
     *
     * @param file
     */
    function handleExcelChange(file: UploadFile) {
        if (file.size !== undefined) {
            if (file.size > 20*1024*1024) {
                ElMessage.warning("上传文件大小不能超过20M");
                return false
            }
        }
        if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
            ElMessage.warning("上传Excel只能为xlsx、xls格式");
            excelFile.value = undefined;
            excelFilelist.value = [];
            return false;
        }
        excelFile.value = file.raw;
    }

    /** 导入提交 */
    function handleImport() {
        if (!excelFile.value) {
            ElMessage.warning("上传Excel文件不能为空");
            return false;
        }
        const importLoading = ElLoading.service({
            lock: true,
            text: '导入中...',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        importNoMatchRecord(excelFile.value).then((response) => {

            closeImportDialog();
            ElMessage.success('导入成功');
            resetQuery();
        }).finally(() => importLoading.close());
    }

    /**  关闭导入弹窗 */
    function closeImportDialog() {
        importDialog.visible = false;
        excelFile.value = undefined;
        excelFilelist.value = [];
    }

    /** 导出转换不到账单记录表 */
    function handleExport() {
        const strIds = [ids.value].join(",");
        exportNoMatchRecord(strIds).then((response: any) => {
            const blob = new Blob([response.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            });
            const a = document.createElement("a");
            const href = window.URL.createObjectURL(blob); // 下载的链接
            a.href = href;
            a.download = decodeURI(
                response.headers["content-disposition"].split(";")[1].split("=")[1]
            ); // 获取后台设置的文件名称
            document.body.appendChild(a);
            a.click(); // 点击导出
            document.body.removeChild(a); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
        });
    }

		function handleReBill() {
			const strIds = [ids.value].join(",");
			reBill(strIds)
			ElMessage.success("操作成功");
			handleQuery();
		}

		function handleReBillAll() {
			ElMessageBox.confirm("确认转换查询结果全部数据?", "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				reBillAll(queryParams)
				ElMessage.success("操作成功");
				handleQuery();
			});
		}

		// 天猫资金流水回炉重造
		function handleFallback() {
			ElMessageBox.confirm("确认转换查询结果全部数据?", "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				queryParams.billType = '天猫资金流水'
				fallback(queryParams)
				ElMessage.success("操作成功");
				handleQuery();
			});
		}

		function handleIgnore() {
			const strIds = [ids.value].join(",");
			ElMessageBox.confirm("确认忽略已选中的数据项?", "警告", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				ignoreBill(strIds).then((response) => {
					ElMessage.success("操作成功");
					handleQuery();
				})
			});
		}

		// 关闭修复弹窗
		function closeRepairDialog() {
			repairDialog.visible = false
		}

    onMounted(() => {
        handleQuery();
				getAllStore()
    });
</script>

<template>
    <div class="app-container">
        <div class="search-container">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
								<el-form-item label="操作时间">
									<el-date-picker
										style="width: 250px"
										v-model="dateList"
										type="daterange"
										clearable
										range-separator="至"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										value-format="YYYY-MM-DD"
									/>
								</el-form-item>
								<el-form-item label="店铺名称" prop="storeId">
									<el-select v-model="queryParams.storeId" class="yz-el-select" filterable clearable placeholder="请选择店铺">
										<el-option-group
											v-for="group in filterStoreList"
											:key="group.label"
											:label="group.label"
										>
											<el-option
												v-for="item in group.options"
												:key="item.id"
												:label="item.commercePlatformStoreName"
												:value="item.id"
											/>
										</el-option-group>
									</el-select>
								</el-form-item>
								<el-form-item label="账单月份" prop="billMonth">
									<el-input
										v-model="queryParams.billMonth"
										placeholder="请输入账单月份"
										clearable
										style="width: 150px"
										@keyup.enter="handleQuery"
									/>
								</el-form-item>
								<el-form-item v-if="activeTab === 'one'" label="原始单据类型" prop="billType">
									<el-input
										v-model="queryParams.billType"
										placeholder="请输入原始单据类型"
										clearable
										style="width: 150px"
										@keyup.enter="handleQuery"
									/>
								</el-form-item>
								<el-form-item label="原始单据ID" prop="dataId">
									<el-input
										v-model="queryParams.dataId"
										placeholder="请输入原始单据ID"
										clearable
										style="width: 150px"
										@keyup.enter="handleQuery"
									/>
								</el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery()"
                    ><i-ep-search />搜索</el-button
                    >
                    <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-card shadow="never">
            <template #header>
                <div class="flex justify-between">
                    <div>
                        <el-button
                                v-hasPerm="['sys:noMatchRecord:save']"
                                type="success"
                                @click="openDialog()"
                        ><i-ep-plus />新增</el-button
                        >
                        <el-button
                                type="danger"
                                :disabled="ids.length === 0"
                                @click="handleDelete()"
                                v-hasPerm="['sys:noMatchRecord:delete']"
                        ><i-ep-delete />删除</el-button
                        >
                    </div>
                    <div>
                        <el-button v-if="activeTab === 'one'" type="danger" :disabled="ids.length === 0" @click="handleIgnore" v-hasPerm="['sys:noMatchRecord:ignore']"
                        >忽略</el-button
                        >
                        <el-button v-if="activeTab === 'one'" type="danger" :disabled="ids.length === 0" @click="handleReBill" v-hasPerm="['sys:noMatchRecord:reBill']"
                        >重新转换</el-button
                        >
                        <el-button v-if="activeTab === 'one'" type="danger" :disabled="total === 0" @click="handleReBillAll" v-hasPerm="['sys:noMatchRecord:reBillAll']"
                        >全部转换</el-button
                        >
                        <el-button v-if="activeTab === 'two'" type="danger" :disabled="tmTotal === 0" @click="handleFallback" v-hasPerm="['sys:noMatchRecord:fallback']"
                        >回炉重造</el-button
                        >
                    </div>
                </div>
            </template>
						<el-tabs v-model="activeTab" type="border-card" @tab-change="tabChange">
							<el-tab-pane label="所有平台" name="one">
								<el-table
									size="small"
									:header-row-style="{color: 'dimgray'}"
									v-loading="loading"
									highlight-current-row
									:data="noMatchRecordList"
									border
									@selection-change="handleSelectionChange"
									:height="noMatchRecordList && noMatchRecordList.length > 0 ? 500 : 130"
								>
									<el-table-column type="selection" width="40" align="center" show-overflow-tooltip />
									<el-table-column label="店铺" prop="storeName" width="100" show-overflow-tooltip/>
									<el-table-column label="原始单据类型" prop="billType" width="100" show-overflow-tooltip/>
									<el-table-column label="原始单据ID" prop="dataId" width="160" show-overflow-tooltip/>
									<el-table-column label="表名前缀" prop="tableNamePreFix" width="100" show-overflow-tooltip/>
									<el-table-column label="字典类型CODE" prop="dictCode" width="100" show-overflow-tooltip/>
									<el-table-column label="账单月份" prop="billMonth" width="100" show-overflow-tooltip/>
									<el-table-column label="状态" prop="statusName" width="100" show-overflow-tooltip/>
									<el-table-column label="操作时间" prop="updateTime" width="140" show-overflow-tooltip/>
									<el-table-column label="原始数据" width="140">
										<template #default="scope">
											<el-tooltip placement="left">
												<template #content>
													<div v-for="item in Object.keys(scope.row.dataJson)" v-if="scope.row.dataJson !== null && scope.row.dataJson !== undefined" style="margin-bottom: 5px;">
														<div style="width: 30%;float: left; text-align: right">{{item}}：</div>
														<div style="width: 70%;float: left;"><span style="font-weight: bold">{{scope.row.dataJson[item]}}</span></div>
													</div>
												</template>
												<span style="color: red;cursor: pointer">查看</span>
											</el-tooltip>
										</template>
									</el-table-column>
									<el-table-column label="备注" prop="remark" show-overflow-tooltip/>
								</el-table>

								<pagination
									v-if="total > 0"
									v-model:total="total"
									v-model:page="queryParams.pageNum"
									v-model:limit="queryParams.pageSize"
									@pagination="handleQuery"
								/>
							</el-tab-pane>
							<el-tab-pane label="天猫资金流水" name="two">
								<el-table
									size="small"
									:header-row-style="{color: 'dimgray'}"
									v-loading="tmLoading"
									highlight-current-row
									:data="noMatchRecordList"
									border
									@selection-change="handleSelectionChange"
									:height="noMatchRecordList && noMatchRecordList.length > 0 ? 500 : 130"
								>
									<el-table-column label="店铺" prop="storeName" width="100" show-overflow-tooltip/>
									<el-table-column label="原始单据类型" prop="billType" width="100" show-overflow-tooltip/>
									<el-table-column label="原始单据ID" prop="dataId" width="160" show-overflow-tooltip/>
									<el-table-column label="商户订单号" prop="sellerOrderNo" width="160" show-overflow-tooltip/>
									<el-table-column label="表名前缀" prop="tableNamePreFix" width="100" show-overflow-tooltip/>
									<el-table-column label="字典类型CODE" prop="dictCode" width="100" show-overflow-tooltip/>
									<el-table-column label="账单月份" prop="billMonth" width="100" show-overflow-tooltip/>
									<el-table-column label="状态" prop="statusName" width="100" show-overflow-tooltip/>
									<el-table-column label="操作时间" prop="updateTime" width="140" show-overflow-tooltip/>
									<el-table-column label="原始数据" width="140">
										<template #default="scope">
											<el-tooltip placement="left">
												<template #content>
													<div v-for="item in Object.keys(scope.row.dataJson)" v-if="scope.row.dataJson !== null && scope.row.dataJson !== undefined" style="margin-bottom: 5px;">
														<div style="width: 30%;float: left; text-align: right">{{item}}：</div>
														<div style="width: 70%;float: left;"><span style="font-weight: bold">{{scope.row.dataJson[item]}}</span></div>
													</div>
												</template>
												<span style="color: red;cursor: pointer">查看</span>
											</el-tooltip>
										</template>
									</el-table-column>
									<el-table-column label="备注" prop="remark" show-overflow-tooltip/>
								</el-table>

								<pagination
									v-if="tmTotal > 0"
									v-model:total="tmTotal"
									v-model:page="queryParams.pageNum"
									v-model:limit="queryParams.pageSize"
									@pagination="handleQuery"
								/>
							</el-tab-pane>
						</el-tabs>

        </el-card>

        <el-dialog
                v-model="dialog.visible"
                :title="dialog.title"
                width="500px"
                :close-on-click-modal="false"
                @close="closeDialog"
        >
            <el-form
                    ref="dataFormRef"
                    :model="formData"
                    :rules="rules"
                    label-width="150px"
            >
                    <el-form-item label="店铺ID" prop="storeId">
                        <el-input v-model="formData.storeId" placeholder="请输入店铺ID" clearable/>
                    </el-form-item>
                    <el-form-item label="原始单据id" prop="dataId">
                        <el-input v-model="formData.dataId" placeholder="请输入原始单据id" clearable/>
                    </el-form-item>
                    <el-form-item label="表名前缀" prop="tableNamePreFix">
                        <el-input v-model="formData.tableNamePreFix" placeholder="请输入表名前缀" clearable/>
                    </el-form-item>
                    <el-form-item label="字典类型CODE" prop="dictCode">
                        <el-input v-model="formData.dictCode" placeholder="请输入字典类型CODE" clearable/>
                    </el-form-item>
                    <el-form-item label="账单月份" prop="billMonth">
                        <el-input v-model="formData.billMonth" placeholder="请输入账单月份" clearable/>
                    </el-form-item>
                    <el-form-item label="原始数据" prop="dataMap">
                        <el-input v-model="formData.dataMap" placeholder="请输入原始数据" clearable/>
                    </el-form-item>
                    <el-form-item label="0 未删除 1 已删除" prop="deleted">
                        <el-input v-model="formData.deleted" placeholder="请输入0 未删除 1 已删除" clearable/>
                    </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                    <el-button @click="closeDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入弹窗 -->
        <el-dialog
                v-model="importDialog.visible"
                :title="importDialog.title"
                width="600px"
                append-to-body
                @close="closeImportDialog"
        >
            <el-form label-width="80px">
                <el-form-item label="Excel">
                    <el-upload
                            class="upload-demo"
                            action=""
                            drag
                            :auto-upload="false"
                            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                            :file-list="excelFilelist"
                            :on-change="handleExcelChange"
                            :limit="1"
                    >
                        <el-icon class="el-icon--upload">
                            <i-ep-upload-filled/>
                        </el-icon>
                        <div class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">xls/xlsx files</div>
                        </template>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleImport">确 定</el-button>
                    <el-button @click="closeImportDialog">取 消</el-button>
                </div>
            </template>
        </el-dialog>

			<el-dialog
				v-model="repairDialog.visible"
				:title="repairDialog.title"
				width="800px"
				:close-on-click-modal="false"
				@close="closeRepairDialog"
			>
				<el-form
					ref="dataFormRef"
				>
					<div v-for="item in Object.keys(dataJson)" v-if="dataJson !== null && dataJson !== undefined" style="margin-bottom: 5px;"><span>{{item}}:<span style="font-weight: bold">{{dataJson[item]}}</span></span><br></div>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="closeRepairDialog">取 消</el-button>
					</div>
				</template>
			</el-dialog>
    </div>
</template>
